package cn.ctbu.edu.labtest.webapi;

import cn.ctbu.edu.labtest.core.PageUtils;
import cn.ctbu.edu.labtest.domain.student;
import cn.ctbu.edu.labtest.service.StudentService;
import net.bytebuddy.TypeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {

    @Autowired
    private StudentService studentService;
    /*读取的url:/webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public List<student> getAll(){
        List<student> students=studentService.findAll();

        return students;
    }
    /*分页读取全部内容
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(
            @RequestParam(value = "page",defaultValue = "0")Integer page,
            @RequestParam(value = "size",defaultValue = "10")Integer size,
                                @RequestParam(value = "name",defaultValue = "")String name){
        Sort sort=Sort.by(Sort.Direction.DESC,"id");
        Page<student> studentPage;
        if(StringUtils.isEmpty(name)){
            Pageable pageable=PageRequest.of(page,size,sort);
            studentPage=studentService.findAll(pageable);
        }else{
            student student=new student();
            student.setName(name);

            Pageable pageable=PageRequest.of(0,10,sort);
            ExampleMatcher matcher=ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<student> example=Example.of(student,matcher);

            studentPage =studentService.findAll(example,pageable);
        }

        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }
    /*读取的url:/webapi/student/get/id
     * @return
     */
    @GetMapping("/get/{id}")
    public student get(@PathVariable Long id){
        student student=studentService.getById(id);
        student.setPassword("");
        return student;
    }

    /*
     * 新增学生的方法。
     */
    @PostMapping("/insert")
    public student insert(student student){

        student student1=studentService.insert(student);
        return student1;

    }

    /*
     * 跟新学生的方法。
     */
    @PutMapping("/update")
    public student update(student student){

        student oldstudent=studentService.getById(student.getId());
        if(StringUtils.isEmpty(student.getPassword())){
            //没有新的就用旧的密码
            student.setPassword(oldstudent.getPassword());
        }
        student=studentService.update(student);

        return student;

    }

    /*
     * 删除学生的方法。
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Long id)
    {
        studentService.delete(id);
    }

}
